package com.isoft.demo01.service.impl;


import com.isoft.demo01.bean.ResultCode;
import com.isoft.demo01.dao.ManageDao;
import com.isoft.demo01.entity.Manage;
import com.isoft.demo01.util.PwdSaltUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ManageService {
    @Autowired
    ManageDao manageDao;
    public boolean add(String name) {
        if(StringUtil.isNullOrEmpty(name)) {
            return false ;
        }
        String salt = PwdSaltUtil.getSalt() ;
        String pwd = null;
        try {
            pwd = PwdSaltUtil.getEncryptedPwd(name ,salt) ;
        } catch (Exception e) {
            e.printStackTrace();
            return false ;
        }
        return manageDao.add(name,pwd,salt) > 0;
    }

    public Map<String , Object> login(String name , String pwd) {
        Map<String , Object> map = new HashMap<>() ;
        if(StringUtil.isNullOrEmpty(name) || StringUtil.isNullOrEmpty(pwd)) {
            map.put("errorCode" , ResultCode.USER_ACCOUNT_NOT_EXIST.getCode()) ;
            return map ;
        }
        // 账号存在检测
        Manage manage = manageDao.chackName(name);
        if(null == manage){  // 账号不存在
            map.put("errorCode" , ResultCode.USER_ACCOUNT_NOT_EXIST.getCode()) ;
            return map ;
        } else { // 账号存在
            if(manage.getState() == Manage.STATE_DISABLE) {   // 账号不可用
                map.put("errorCode" , ResultCode.USER_ACCOUNT_DISABLE.getCode());
                return map ;
            } else {
                String salt = manage.getSalt() ;
                String pwdDB = manage.getPassword() ;
                try {
                    boolean isOk = PwdSaltUtil.validPassword(pwd , salt , pwdDB) ;
                    if(isOk) {
                        map.put("errorCode" , ResultCode.SUCCESS.getCode()) ;
                        map.put("data" , manage) ;
                        return map ;
                    } else {
                        map.put("errorCode" , ResultCode.USER_CREDENTIALS_ERROR.getCode()) ;
                        return map ;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    map.put("errorCode" , ResultCode.COMMON_FAIL.getCode()) ;
                    return map ;
                }
            }
        }

    }
}
